<template>
  <el-config-provider :locale="locale" :size="size">
    <!-- 开启水印 -->
    <el-watermark v-if="watermarkEnabled" :font="{ color: fontColor }" :content="defaultSettings.watermarkContent"
      class="wh-full">
      <router-view />
    </el-watermark>
    <!-- 关闭水印 -->
    <router-view v-else />
  </el-config-provider>
</template>

<script setup>
import { useAppStore, useSettingsStore, useUserStore, useHintStore } from "@/stores";
import { defaultSettings, ThemeEnum, SizeEnum } from "@/settings";
import { setupEcho } from "@/plugins/echo";
import { watch } from "vue";
import sound from '@/assets/audio/hint.mp3'
import { useRouter } from "vue-router";
const appStore = useAppStore();
const settingsStore = useSettingsStore();
const userStore = useUserStore()
const locale = computed(() => appStore.locale);
const size = computed(() => appStore.size);
const watermarkEnabled = computed(() => settingsStore.watermarkEnabled);

// 明亮/暗黑主题水印字体颜色适配
const fontColor = computed(() => {
  return settingsStore.theme === ThemeEnum.DARK
    ? "rgba(255, 255, 255, .15)"
    : "rgba(0, 0, 0, .15)";
});
// setupEcho
watch(() => userStore.token, (e) => {
  console.log('tokens======', e);
  if (e) {
    // addEcho()
  }
})
watch(() => userStore.openEcho, (e) => {
  console.log('tokens======', e);
  if (e) {
    addEcho()
  } else {
    Echo.leave(`withdrawals`);
  }
})

const hintStore = useHintStore()
const router = useRouter()
const addEcho = () => {
  setupEcho()
  Echo.private('withdrawals').listen('WithdrawalCreated', (e) => {
    ElNotification({
      // title: 'Prompt',
      dangerouslyUseHTMLString: true,
      message: t('hint.101', { user: e.withdrawal.user_id, num: e.withdrawal.amount }),
      duration: 5000,
      onClick: () => {
        ElNotification.closeAll()
        router.push('/record/withdraw')
      }
    })
    hintStore.setHint('withdrawal', e.withdrawal)
    toggleAudio()
    console.log('withdrawals===', e)
  })
}

// 提示音
const audio = new Audio(sound)
audio.onended = () => {
  playing.value = false
}
const playing = ref(false)
const toggleAudio = () => {
  if (!playing.value) {
    playing.value = true
    audio.play()
  }
}
onMounted(() => {
  if (userStore.token) {
    // addEcho()
  }
  if (appStore.language.split('-')[0] !== appStore.language) {
    appStore.changeLanguage(appStore.language.split('-')[0])
    window.location.reload()
  }
})
onUnmounted(() => {
  Echo.leave(`withdrawals`);
})
</script>
